﻿<html>
<head>
    <script
        src="https://code.jquery.com/jquery-1.12.4.min.js"
        integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
        crossorigin="anonymous"></script>
</head>
<body>
<div style="width: 40%; float: left">
    <div id="sysMsg" style="width: 100%; height: 100%"></div>
</div>
<div style="width: 60%; float: left">
    <div>
        昵称：<input type="text" id="nickname"/>
        <button id="btnConn">连接</button>
        @* <button id="btnBreak">断开</button> *@
        <label id="lblState"></label>
    </div>
    <div>
        用户Id:<input type="text" id="txtUserId"/>
        消息：<textarea type="text" id="txtMessage"></textarea>
        <button id="btnSendMessage">发送</button>
    </div>
    <div>
        私信：
        <div id="privateMsg" style="width: 100%; height: 80%"></div>
    </div>
</div>

</body>
</html>

<script type="text/javascript">
    String.prototype.startWith = function(str) {
        if (str == null || str == "" || this.length == 0 || str.length > this.length) {
            return false;
        }
        if (this.substr(0, str.length) == str) {
            return true;
        } else {
            return false;
        }
        return true;
    };

    $(function() {
        var ws;
        var lockReconnect = false; //避免重复连接
        var wsUrl;

        function createWebSocket(url) {
            try {
                if ('WebSocket' in window) {
                    ws = new WebSocket(url);
                } else if ('MozWebSocket' in window) {
                    ws = new MozWebSocket(url);
                }
                initEventHandle();
            } catch (e) {
                reconnect(url);
            }
        }

        //心跳检测
        var heartCheck = {
            timeout: 50000, //50秒
            timeoutObj: null,
            serverTimeoutObj: null,
            reset: function() {
                clearTimeout(this.timeoutObj);
                clearTimeout(this.serverTimeoutObj);
                return this;
            },
            start: function() {
                var self = this;
                this.timeoutObj = setTimeout(function() {
                        //这里发送一个心跳，后端收到后，返回一个心跳消息，
                        //onmessage拿到返回的心跳就说明连接正常
                        ws.send("HeartBeat");
                        self.serverTimeoutObj = setTimeout(function() { //如果超过一定时间还没重置，说明后端主动断开了
                                ws.close(); //如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                            },
                            self.timeout);
                    },
                    this.timeout);
            }
        }


        function initEventHandle() {
            ws.onclose = function(evnt) {
                $("#lblState").text("已断开");
                reconnect(wsUrl);
            };
            ws.onerror = function(evnt) {
                //console.log('websocket服务出错了');
                reconnect(wsUrl);
            };
            ws.onopen = function(evnt) {
                $("#lblState").text("已连接");
                heartCheck.reset().start();
            };
            ws.onmessage = function(evnt) {
                //如果获取到消息，心跳检测重置
                //拿到任何消息都说明当前连接是正常的
                //console.log('websocket服务获得数据了');

                //接受消息后的UI变化
                doWithMsg(evnt.data);
                heartCheck.reset().start();
            }

            //收到消息推送
            function doWithMsg(msg) {
                console.log(msg);
                if (msg.startWith('{')) {
                    let msgObj = JSON.parse(msg);
                    if (msgObj.messageName == 'SendToUser') {
                        let contentObj = JSON.parse(msgObj.content);

                        $("#privateMsg").append($("<p>" +
                            contentObj.time +
                            "    " +
                            contentObj.fromUserId +
                            "说：   " +
                            contentObj.content +
                            "</p>"));
                    }
                } else {
                    $("#sysMsg").append($("<p>" + msg + "</p>"));
                }

            }

        }

        function reconnect(url) {
            if (lockReconnect) return;
            lockReconnect = true;
            //没连接上会一直重连，设置延迟避免请求过多
            setTimeout(function() {
                    createWebSocket(url);
                    lockReconnect = false;
                },
                2000);
        }


        $("#btnConn").on('click',
            function() {
                let nickName = $("#nickname").val();

                $.get('/home/CreateConnectionRequest',
                    { nickname: nickName },
                    function(res) {

                        wsUrl =
                            `ws://127.0.0.1:8080/ws?sign=${res.sign}&userid=${res.userId}&timestamp=${res.timestamp}`;

                        createWebSocket(wsUrl);

                        $("#btnConn").attr("disabled", "disabled");

                    });
            });

        $("#btnSendMessage").on('click',
            function() {
                let sendToUserCommand = {
                    toUserId: $("#txtUserId").val(),
                    content: $("#txtMessage").val()
                };
                let command = {
                    commandName: 'SendToUser',
                    content: JSON.stringify(sendToUserCommand)
                };

                ws.send(JSON.stringify(command));
            });
    });
</script>